package com.atguigu.gmall.realtime.app.dwd.db;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.TableProcess;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.FlinkSinUtil;
import com.atguigu.gmall.realtime.util.JdbcUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Connection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

/**
 * @Author lzc
 * @Date 2023/2/15 13:48
 */
@Slf4j
public class Dwd_08_BaseDBApp extends BaseApp {
    public static void main(String[] args) {
        new Dwd_08_BaseDBApp().init(
            3008,
            2,
            "Dwd_08_BaseDBApp",
            Constant.TOPIC_ODS_DB
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 对数据做 etl
        SingleOutputStreamOperator<JSONObject> dataStream = etl(stream);
        
        // 2. 读取配置信息
        SingleOutputStreamOperator<TableProcess> tpStream = readTableProcess(env);
        // 3. 让数据流和配置流进行 connect
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcess>> dataTpStream = connect(dataStream, tpStream);
        // 4. 去除不需要的列
        dataTpStream = delNotNeedColumns(dataTpStream);
        // 5. 写出到 kafka 中
        writeToKafka(dataTpStream);
    }
    
    private void writeToKafka(SingleOutputStreamOperator<Tuple2<JSONObject, TableProcess>> dataTpStream) {
        dataTpStream.addSink(FlinkSinUtil.getKafkaSink());
    }
    
    private SingleOutputStreamOperator<Tuple2<JSONObject, TableProcess>> delNotNeedColumns(
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcess>> dataTpStream) {
        // ({"a": '', "b:":..}, Tp..)  =>({"a": ''}, Tp..)
        return dataTpStream
            .map(new MapFunction<Tuple2<JSONObject, TableProcess>, Tuple2<JSONObject, TableProcess>>() {
                @Override
                public Tuple2<JSONObject, TableProcess> map(Tuple2<JSONObject, TableProcess> t) throws Exception {
                    JSONObject data = t.f0;
                    List<String> columns = Arrays.asList(t.f1.getSinkColumns().split(","));
                    // 遍历 data 中的每一个 key, 如果在columns中存在就保留, 不存在就删除
                    data.keySet().removeIf(key -> !columns.contains(key) && !"operate_type".equals(key));
                    
                    return t;
                }
            });
        
    }
    
    private SingleOutputStreamOperator<Tuple2<JSONObject, TableProcess>> connect(
        SingleOutputStreamOperator<JSONObject> dataStream,
        SingleOutputStreamOperator<TableProcess> tpStream) {
        // 1. 先把配置流做成广播流
        // key: source_table:table_name   user_info:update
        // value:  TableProcess
        MapStateDescriptor<String, TableProcess> tpStateDesc = new MapStateDescriptor<>("tpState", String.class, TableProcess.class);
        BroadcastStream<TableProcess> tpBcStream = tpStream.broadcast(tpStateDesc);
        // 2. 数据流去 connect 广播流
        BroadcastConnectedStream<JSONObject, TableProcess> dataTpStream = dataStream.connect(tpBcStream);
        
        
        return dataTpStream
            .process(new BroadcastProcessFunction<JSONObject, TableProcess, Tuple2<JSONObject, TableProcess>>() {
                
                private HashMap<String, TableProcess> tpMap;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    // 先去读取所有配置信息: 预加载
                    // 数据读进来之后,存储到哪里?  能不能存储到广播状态中? 不能.因为在 open 中不能操作状态
                    // 存储到一个map 集合中
                    tpMap = new HashMap<>();
                    // 通过 jdbc 的方式从配置表中读取配置
                    Connection conn = JdbcUtil.getMySqlConnection();
                    // 查询配置信息
                    // id  name  age
                    // 1   zs   10
                    // 2   lisi  10
                    String querySql = "select * from gmall_config.table_process";
                   
                    List<TableProcess> list = JdbcUtil.queryList(conn, querySql, null, TableProcess.class);
                    for (TableProcess tp : list) {
                        String key = getStateKey(tp.getSourceTable(), tp.getSourceType(), tp.getSinkExtend());
                        tpMap.put(key, tp);
                    }
                    JdbcUtil.closeConnection(conn);
                    
                }
                
                // 4. 处理数据流中的数据(维度数据后): 从广播中状态对找到每条数据对应的配置信息.
                // 数据流中的数据, 每来一条, 会执行一次
                @Override
                public void processElement(JSONObject value,
                                           ReadOnlyContext ctx,
                                           Collector<Tuple2<JSONObject, TableProcess>> out) throws Exception {
                    ReadOnlyBroadcastState<String, TableProcess> state = ctx.getBroadcastState(tpStateDesc);
                    String table = value.getString("table");
                    String type = value.getString("type");
                    String extend = "";
                    // 当表示 coupon_use 并且 是 update, 并且是从 1401->1402, extend = {"data": {"coupon_status": "1402"}, "old": {"coupon_status": "1401"}}
                    // 当表示 coupon_use 并且 是 update, 并且是从 used_time 不是 null extend={"data": {"used_time": "not null"}}
                    if ("coupon_use".equals(table) && "update".equals(type)) {
                        JSONObject data = value.getJSONObject("data");
                        JSONObject old = value.getJSONObject("old");
                        
                        // 表示下单的时候使用了优惠券
                        if ("1401".equals(old.getString("coupon_status")) && "1402".equals(data.getString("coupon_status"))) {
                            extend = "{\"data\": {\"coupon_status\": \"1402\"}, \"old\": {\"coupon_status\": \"1401\"}}";
                        } else if (data.getString("used_time") != null) {
                            extend = "{\"data\": {\"used_time\": \"not null\"}}";
                        }
                    }
                    
                    String key = getStateKey(table, type, extend);
                    //System.out.println("key: " + key);
                    
                    // 先从状态读取, 如果读不到再从 map, 因为状态一定是最新的
                    TableProcess tp = state.get(key);
                    // tp == null 表示状态中没有获取配置: 1. 配置没来  2.没有这条数据的配置
                    if (tp == null) {
                        System.out.println("状态中没有读取到配置: " + table);
                        tp = tpMap.get(key);
    
                        if (tp == null) {
                            System.out.println("预加载的 map 中也没有读取到配置: " + table);
                        }
                    }
                    
                    if (tp != null) { // 这条数据有对应的配置信息
                        JSONObject data = value.getJSONObject("data");
                        // 后面有用
                        data.put("operate_type", value.getString("type"));
                        out.collect(Tuple2.of(data, tp));
                    }
                }
                
                // 3. 处理广播流的数据: 把配置信息放入到广播状态中
                // 每来一条配置信息, 则每个并行度执行一次这个方法
                @Override
                public void processBroadcastElement(TableProcess tp,
                                                    Context ctx,
                                                    Collector<Tuple2<JSONObject, TableProcess>> out) throws Exception {
                    // 获取到广播状态
                    BroadcastState<String, TableProcess> state = ctx.getBroadcastState(tpStateDesc);
                    // 把配置信息存入到广播状态
                    String key = getStateKey(tp.getSourceTable(), tp.getSourceType(), tp.getSinkExtend());
                    
                    // 如果 op=d, 把配置从广播状态中删除
                    // 其他的是更新或者新增
                    if ("d".equals(tp.getOp_type())) {
                        state.remove(key);
                        tpMap.remove(key);
                    } else {
                        state.put(key, tp);
                    }
                }
                
                private String getStateKey(String table, String type, String extend) {
                    return table + ":" + type + ":" + (extend == null ? "" : extend);
                }
            });
        
        
    }
    
    private SingleOutputStreamOperator<TableProcess> readTableProcess(StreamExecutionEnvironment env) {
        Properties props = new Properties();
        props.put("useSSL", "false");
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
            .hostname("hadoop162")
            .port(3306)
            .databaseList("gmall_config") // set captured database, If you need to synchronize the whole database, Please set tableList to ".*".
            .tableList("gmall_config.table_process") // set captured table
            .username("root")
            .password("aaaaaa")
            .jdbcProperties(props)
            .startupOptions(StartupOptions.initial()) // 启动读取所有数据, 然后再从 binlog 读取变化数据
            .deserializer(new JsonDebeziumDeserializationSchema()) // converts SourceRecord to JSON String
            .build();
        
        return env
            .fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql-config-source")
            .map(new MapFunction<String, TableProcess>() {
                @Override
                public TableProcess map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    // d: 需要 before
                    // c,r,u: 需要 after
                    String op = obj.getString("op");
                    TableProcess tp;
                    if ("d".equals(op)) {
                        tp = obj.getObject("before", TableProcess.class);
                    } else {
                        tp = obj.getObject("after", TableProcess.class);
                    }
                    tp.setOp_type(op);
                    
                    return tp;
                }
            })
            .filter(tp -> "dwd".equals(tp.getSinkType()));
        
    }
    
    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
        return stream
            .filter(new FilterFunction<String>() {
                @Override
                public boolean filter(String value) throws Exception {
                    
                    // 应该是 json 格式
                    try {
                        JSONObject obj = JSON.parseObject(value);
                        String type = obj.getString("type");
                        String data = obj.getString("data");
                        return "gmall2022".equals(obj.getString("database"))
                            && null != obj.getString("table")
                            && ("insert".equals(type) || "update".equals(type))
                            && null != data
                            && data.length() > 2;
                    } catch (Exception e) {
                        // 不是 json 格式
                        log.warn("你的 json 数据: " + value + "  不是正确的 json");
                        return false;
                    }
                }
            })
            .map(JSON::parseObject);
        
    }
}
/*
交互域
工具域
用户域

-------

复杂表
	流量域: 5 个日志的分流

	交易域:
		加购
		下单
		取消订单
		支付成功
		退单
		退款成功


简单表
	动态分流

		交互域
			评论
			收藏
		工具域
			优惠券领用
			优惠券下单
			优惠券支付
		用户域
			用户的注册
 */